package org.klaoye.musicplayer;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import org.klaoye.musicplayer.bean.FileSelector;
import org.klaoye.musicplayer.bean.ReceiverStrings;
import org.klaoye.musicplayer.bean.Tools;

import java.io.File;
import java.io.FileFilter;

public class PlayerFragment extends Fragment implements AdapterView.OnItemClickListener, View.OnClickListener, View.OnTouchListener, ReceiverStrings {

    ImageButton playBtn, lastBtn, nextBtn, listsBtn;
    ListView musicListView;//列表视图
    boolean isPlaying = false;
    File parentsPath = null;
    File chooseFile = null;
    File[] itemFiles;
    Intent musicIntent;
    Binder musicBinder;
    FileSelector selector;
    Bundle bundle;
    FileFilter filter;
    IntentFilter intentFilter;
    BroadcastReceiver receiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        musicIntent = new Intent(getContext(), MusicService.class);
        musicBinder = new Binder();
        selector = new FileSelector(getContext());
        bundle = getArguments();
        filter = file -> file.isFile();
        intentFilter = new IntentFilter(BROADCAST_SERVICE);
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String s = intent.getStringExtra(FLAG_STRING);
                ListAdapter adapter = musicListView.getAdapter();
                int i = 0;
                for (File f : itemFiles) {
                    if (f.getName().equals(s)) break;
                    i++;
                }
                //i = musicListView.getSelectedItemPosition();
                for (int p = 0; p < musicListView.getChildCount(); p++) {
                    View view = musicListView.getChildAt(p);
                    if (view.getDrawingCacheBackgroundColor() == Color.WHITE) continue;
                    if (p == i) {
                        view.setBackgroundColor(Color.GREEN);
                    } else {
                        view.setBackgroundColor(Color.WHITE);
                    }
                }
            }
        };
        getContext().registerReceiver(receiver, intentFilter);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_player, container, false);

        playBtn = v.findViewById(R.id.btn_play);
        lastBtn = v.findViewById(R.id.btn_last);
        nextBtn = v.findViewById(R.id.btn_next);
        listsBtn = v.findViewById(R.id.btn_lists);
        musicListView = v.findViewById(R.id.music_list_view);

        playBtn.setOnClickListener(this);
        lastBtn.setOnClickListener(this);
        nextBtn.setOnClickListener(this);
        listsBtn.setOnClickListener(this);

        playBtn.setOnTouchListener(this);
        lastBtn.setOnTouchListener(this);
        nextBtn.setOnTouchListener(this);
        listsBtn.setOnTouchListener(this);

        musicListView.setOnItemClickListener(this);
        selector.setListView(musicListView);
        itemFiles = selector.listFile(parentsPath, filter);

        return v;
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    public void onClick(View v) {
        ImageButton btn = (ImageButton) v;
        btn.setImageAlpha(255);
        isPlaying = !isPlaying;
        Intent broadcast = new Intent(BROADCAST_ACTIVITY);
        switch (v.getId()) {
            case R.id.btn_next:
                broadcast.putExtra(FLAG_INT, NEXT);
                break;
            case R.id.btn_last:
                broadcast.putExtra(FLAG_INT, LAST);
                break;
            case R.id.btn_lists:
                break;
            case R.id.btn_play:
                if (!Tools.isServiceRunning(getContext(), "org.klaoye.musicplayer.MusicService")) {
                    Intent intent = new Intent(getContext(), MusicService.class);
                    intent.setData(Uri.fromFile(parentsPath));
                    getContext().startService(intent);
                }
                if (!isPlaying) {
                    btn.setImageDrawable(getResources().getDrawable(R.drawable.ic_play));
                    //getContext().stopService(musicIntent);
                } else {
                    btn.setImageDrawable(getResources().getDrawable(R.drawable.ic_suspend));

                }
                if (isPlaying) {
                    broadcast.putExtra(FLAG_INT, PLAY);
                } else {
                    broadcast.putExtra(FLAG_INT, PAUSE);
                }
                //itemFiles = selector.listFile(parentsPath,filter);
                break;
        }
        getActivity().sendBroadcast(broadcast);
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        ImageButton btn = (ImageButton) v;
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                btn.setImageAlpha(100);
                break;
            case MotionEvent.ACTION_UP:
                btn.setImageAlpha(255);
                break;
        }
        return false;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        MainActivity mainActivity = (MainActivity) context;
        parentsPath = mainActivity.currentFile;
        bundle = mainActivity.bundle;
        parentsPath = new File(bundle.getString("file_path"));

        Intent intent = new Intent(getContext(), MusicService.class);
        intent.setData(Uri.fromFile(parentsPath));
        getContext().startService(intent);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        chooseFile = itemFiles[position];
        Intent intent = new Intent(getActivity(), MusicService.class);
        intent.setData(Uri.fromFile(chooseFile));
        getActivity().startService(intent);
    }

}